import $ from 'jquery'
class Unit {//通过父类保存参数
    constructor(element){
        this.currentElement=element;
    }
}
//负责渲染文本
class ReactTextUnit extends Unit {
    getMarkUp(rootId) {//保存当前元素的id
        this._rootId = rootId;
        // 并且返回当前元素对应的html脚本
        return `<span data-reactid="${rootId}">${this.currentElement}</span>`;
    }
}
//负责渲染html
class ReactNativeUnit extends Unit {
    getMarkUp(rootId) {//保存当前元素的id
        this._rootId = rootId;
        //拼接需要渲染的内容

        let {type,props}=this.currentElement;
        let tagStart=`<${type} data-reactid="${rootId}"`;
        let tagEnd=`</${type}>`;
        let contentStr;
        for(let propName in props){
            if(/on[A-Z]/.test(propName)){
                let eventType=propName.slice(2).toLowerCase();
                //reactl里面的事件是通过事件委托来绑定
                //替换
                $(document).on(eventType,`[data-reactid="${rootId}"]`,props[propName]);
            }else if(propName ==='children'){
                contentStr= props[propName].map((child,idx)=>{
                    //递归循环子节点
                  let childInstance=createReactUnit(child);
                 return   childInstance.getMarkUp(`${rootId}.${idx}`)
                }).join('')
            }else{
                tagStart+=(`${propName} = ${props[propName]}`)
            }
        }
        //返回拼接后的字符串
        return tagStart+'>'+contentStr+tagEnd
    }
}
//负责渲染react组件的
class ReactCompositUnit extends Unit {
    getMarkUp(rootId) {//保存当前元素的id
        this._rootId = rootId;
        let {type:Component,props}=this.currentElement;
        let componentInstance=new Component(props);//Component为element中的type
        componentInstance.componmentWillMount&&componentInstance.componmentWillMount();

        //调用render返回的结果
       let reactComponentRender=componentInstance.render();//0
        //递归渲染 组件后的返回结果
        let reactCompositUnitInstance=createReactUnit(reactComponentRender);
        let markUp= reactCompositUnitInstance.getMarkUp(rootId);
        //在递归后绑定事件 先触发儿子
        $(document).on('mounted',on=>{
            componentInstance.componmentDidMount&&componentInstance.componmentDidMount();
        })
        return markUp;
    }
}
function createReactUnit(element){

    if(typeof  element==='string'||typeof  element==='number'){
        return new ReactTextUnit(element)
    }
    if(typeof  element==='object'&&typeof  element.type==='string'){
        return new ReactNativeUnit(element)
    }
    if(typeof  element==='object'&&typeof  element.type==='function'){
        return new ReactCompositUnit(element) //{type:Counter,{name:XXx}}
    }
}
export  default createReactUnit;